<template>
	<view class="yz" ref="yz">
		<scroll-view scroll-x class="tag-nav nav text-center">
			<view class="cu-item" :class="0 == TabCur ? 'text-blue cur' : ''" @tap="tabSelect" data-id="0">热门</view>
			<view class="cu-item" :class="1 == TabCur ? 'text-blue cur' : ''" @tap="tabSelect" data-id="1">推荐</view>
			<view class="cu-item" :class="2 == TabCur ? 'text-blue cur' : ''" @tap="tabSelect" data-id="2">视频</view>
			<view class="cu-item" :class="3 == TabCur ? 'text-blue cur' : ''" @tap="tabSelect" data-id="3">文章</view>
			<view class="cu-item" :class="4 == TabCur ? 'text-blue cur' : ''" @tap="tabSelect" data-id="4">语音</view>
		</scroll-view>

		<swiper class="contnet-swiper " ref="contnetSwiper" :current="TabCur" @change="swiperChange" easing-function="easeInOutCubic"
		 duration='300'>
			<!-- 下拉刷新 -->
			<swiper-item class="contnet-swiper-item" @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend">
				<view class="pullRefresh" ref="pullRefresh" :class="isEnd ? 'transition-Zero5' : ''" :style="{ marginTop: marginTop + 'px' }"
				 @touchmove="articleBlockTouchmove" :scroll-top='scrollTop'>
					<view class="text-center flex ali-end just-cent pb40" style="height: 100px;">
						<text class="cuIcon-loading1  mr20 fo-40" :class="loadText === '加载中...' ? 'animation-rotate' : ''"></text>
						<text class="fo-gray fo-32">{{ loadText }}</text>
					</view>
					<!-- 组件引入 -->
					<!-- #ifdef H5 -->
					<transition-group name="list" tag="view">
						<!-- #endif -->
						<Card class="Card" v-for="(i, j) in data_list" :articleList.sync="i" :key="i._id"></Card>
						<!-- #ifdef H5 -->
					</transition-group>
					<!-- #endif -->

					<!-- 加载更多 -->
					<u-loadmore v-if="data_list.length >= 10" class="padd20" :status="LoadMoreStatus" icon-type="flower" :loadText="loadMoreText" />
				</view>
			</swiper-item>
			<swiper-item class="contnet-swiper-item">2</swiper-item>
			<swiper-item class="contnet-swiper-item">3</swiper-item>
			<swiper-item class="contnet-swiper-item">4</swiper-item>
			<swiper-item class="contnet-swiper-item">5</swiper-item>
		</swiper>
	</view>
</template>

<script>
	const {
		windowWidth,
		windowHeight
	} = uni.getSystemInfoSync();
	import Card from './Card.vue';
	let StartScrollX,
		StartScrollY,
		MoveScrollY,
		timer,
		timers, // 防止重复触底
		X_OR_Y_MOVE = null; // 判断是上下滑还是左右滑

	let timeToBackTop = null // 子组件和父组件通信 防抖
	import {
		API$SelArticleList
	} from '../../../common/API/community';
	export default {
		name: '',
		components: {
			Card
		},
		data() {
			return {
				TabCur: 0, // tag 栏目下标

				activeColor: this.$u.color['primary'],
				current: 0,
				list: [{
						name: '关注'
					},
					{
						name: '推荐'
					},
					{
						name: '视频'
					},
					{
						name: '语音'
					},
					{
						name: '文章'
					}
				],

				// 下拉刷新需要的数据
				CurrentTopPositon: 0,
				loadText: '下拉刷新',
				marginTop: -100,
				isEnd: false,
				scrollTop: 0, // 缓存scrollTop 是当前滚动条的位置

				data_list: [],
				total: '',

				SelJson: {
					pageNum: 0,
					pageSize: 10
				},

				LoadMoreStatus: 'loadmore', // 加载更多状态
				isLoading: false, // 当前是否触底加载中 加载中不可操作

				loadMoreText: {
					loadmore: '上拉加载更多',
					loading: '正在加载...',
					nomore: '没有更多了'
				},
			};
		},
		created() {
			// 首次加载启动下拉刷新占位刷新
			this.marginTop = -50;
			this.loadText = '加载中...';

			this.getArticleList();
			// 监听修改data_list数组的点赞状态   (本地数据无刷新 后台已刷新)
			uni.$on('FreshArticleList', res => {
				let {
					CallType,
					state,
					ArticleId,
					data,
					_id
				} = res;

				// 改变点赞状态
				if (CallType === 'changeLike') {
					this.data_list.forEach(i => {
						if (i._id === ArticleId) {
							this.$set(i, 'iSlike', state);
							i.iSlike ? this.$set(i, 'likeCount', i.likeCount + 1) : this.$set(i, 'likeCount', i.likeCount - 1)
						}
					});
				}
				// 本数组添加一条新发布的数据
				if (CallType === 'addArticle') {
					this.data_list.unshift(data);
				}

				// 重新刷新数组的某个值
				if (CallType === 'reset') {
					this.data_list.forEach((i, j) => {
						this.$set(i, 'isPlayAudio_ing', false)
						if (i._id === _id) {
							this.$set(i, 'isPlayAudio_ing', true)
							this.$set(i, 'testDiaoYong', i.testDiaoYong + 1)
						}
					})
				}

				// 改变是否展开全部的状态
				if (CallType === 'resetLookAll') {
					this.data_list.forEach((i, j) => {
						if (i._id === _id) {
							this.$set(i, 'isLookAll', true)
						}
					})
				}
			});
		},
		// onUnload() {
		// 	uni.$off('FreshArticleList')
		// },
		methods: {
			// swiper bar点击改变
			tabSelect(e) {
				this.TabCur = e.currentTarget.dataset.id;
				this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60;
			},
			*
			// swiper滑动改变
			swiperChange(e) {
				this.TabCur = e.detail.current;
			},
			// 监控评论节点的触底加载
			articleBlockTouchmove(e) {
				if (this.isLoading) return; // 防止重复触底请求加载
				if (this.data_list.length < 10) return; // 没满10条不让触底加载
				let views = uni.createSelectorQuery().select('.pullRefresh');
				views
					.boundingClientRect(data => {
						let Computeds = windowHeight - 60 - 45 - 20 + 20 + 100 - 44
						//  750 		- 60		 - 45			-20+20			= 645   		 						+ 100			-44		=	700
						//  屏幕高度		导航栏+占位	 tsg页			加载更多高度(这个放在pullRefresh里面的不计算)				margintop:-100	tarbar
						// console.log('bottom:',Math.floor(data.top + data.height));
						// console.log(data.height,'height')
						// console.log(data.top,'top')
						// console.log(Math.floor(Math.floor(data.top + data.height)),Computeds,windowHeight)
						if (Math.floor(Math.floor(data.top + data.height)) <= windowHeight) {
							this.isLoading = true;
							this.LoadMoreStatus = 'loading';
							if (timers) return
							timers = setTimeout(() => {
								if (this.SelJson.pageNum + 1 > Math.floor(this.total / this.SelJson.pageSize)) return (this.LoadMoreStatus =
									'nomore');
								this.SelJson.pageNum++;
								console.log(this.SelJson.pageNum, this.isLoading)
								console.log('触底了');
								this.getArticleList();
							}, 1000)


						}
						// if(Math.floor(data.height) <=  Math.abs((Math.floor(data.top))) +  Math.floor(data.bottom)){}
					})
					.exec();
			},
			/* ********************************************数据处理部分****************************************************/
			// 获取文章列表
			async getArticleList(instruct) {
				try {
					let UserId = this.$pub.getStorageSync('UserInfo')._id;
					let {
						code,
						msg,
						data,
						total
					} = await API$SelArticleList(Object.assign({
						UserId
					}, this.SelJson));
					if (code === 200) {
						// this.$pub.Toast(msg);
						this.total = total;
						data.forEach(i => {
							i['isLookAll'] = false
							i['isPlayAudio_ing'] = false
							i['testDiaoYong'] = 0
						})
						this.data_list = instruct === 'ReFresh' ? data : this.data_list.concat(data);
						// console.log(data);
						this.FreshOk();
					}
				} catch (e) {
					console.error(e);
					this.LoadMoreStatus = 'loadmore';
					this.SelJson.pageNum--;
				} finally {
					timers = null
					this.isLoading = false; // 结束否触底加载中
				}
			},
			/*下拉刷新  封装************************************************************************************************/
			panduan() {
				let views = uni.createSelectorQuery().select('.pullRefresh');
				views
					.boundingClientRect(data => {
						this.CurrentTopPositon = data.top;
					})
					.exec();
			},
			touchstart(e) {
				if (X_OR_Y_MOVE === '左右滑动') return;
				StartScrollX = e.touches[0].clientX;
				StartScrollY = e.touches[0].clientY;

				this.isEnd = false;
			},
			touchmove(e) {
				if (X_OR_Y_MOVE === '左右滑动') return;
				let slideX_distance = e.touches[0].clientX - StartScrollX;
				let slideY_distance = e.touches[0].clientY - StartScrollY;
				Math.abs(slideY_distance) > Math.abs(slideX_distance) ? (X_OR_Y_MOVE = '上下滑动') : (X_OR_Y_MOVE = '左右滑动');
				this.panduan(MoveScrollY);
				MoveScrollY = e.touches[0].clientY - StartScrollY;


				// 改变回到顶部图标
				if (!timeToBackTop) {
					// console.log('touchmove中')
					uni.$emit('$onCommunity', {
						type: "ChangeTopIcon",
						isShowTop: this.CurrentTopPositon < -800 ? true : false
					})
				}
				timeToBackTop = setTimeout(() => {
					clearTimeout(timeToBackTop)
					timeToBackTop = null
				}, 500)



				if (this.CurrentTopPositon >= -97 && MoveScrollY > 0) {
					this.loadText = '下拉刷新';
					// 阻尼系数0.5
					this.marginTop = -100 + MoveScrollY * 0.3;
					if (MoveScrollY > 180) {
						this.loadText = '释放刷新';
					}
				}
			},
			touchend(e) {
				// 下拉强度是180
				if (this.CurrentTopPositon >= -97 && MoveScrollY > 180) {
					this.loadText = '加载中...';
					this.SelJson.pageNum = 0;
					this.getArticleList('ReFresh');
				} else {
					this.isEnd = true;
					this.marginTop = -100;
				}

				X_OR_Y_MOVE = null;
				StartScrollX = null;
				StartScrollY = null;
				MoveScrollY = null;
			},
			// 刷新成功~
			FreshOk() {
				this.isEnd = true;
				this.loadText = '刷新成功~';
				console.log('%c刷新成功', 'color:red');

				this.marginTop = -100;
			},

			// 供父组件调用（搜索按钮）
			ChangeData_list(value) {
				this.total = 10;
				this.data_list = value;
			},
			// 回到顶部(妈的bug)
			backToTop() {
				let views = uni.createSelectorQuery().select('.pullRefresh');
				// console.log(window.scrollX)
				views
					.boundingClientRect(data => {
						console.log(data.top = 10)
					})
					.exec();
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300
				})
			}
		}
	};
</script>

<style lang="less" scoped>
	.yz {
		position: relative;
	}

	.cu-item {
		padding: 0 30rpx;
	}

	.contnet-swiper {
		width: 100%;
		height: 80vh;
	}

	.contnet-swiper-item {
		height: 80vh;
		overflow: scroll;
	}

	// 下拉刷新

	.pullLoad {
		// z-index: -99;
		width: 100%;
		position: absolute;
		top: 0;
	}

	.drownFresh {
		width: 100%;
		background-color: #ebebeb;
		text-align: center;
	}

	.drownFresh-hold,
	.drownFresh-release {
		padding: 20px 0;
	}

	.css-icon {
		display: inline-block;
		height: 1em;
		width: 1em;
		font-size: 20px;
		box-sizing: border-box;
		text-indent: -9999px;
		vertical-align: middle;
		position: relative;
	}

	.css-icon::before,
	.css-icon::after {
		content: '';
		box-sizing: inherit;
		position: absolute;
		left: 50%;
		top: 50%;
		-ms-transform: translate(-50%, -50%);
		transform: translate(-50%, -50%);
	}


	// 列表过渡动画
	.Card {
		transition: all 1s;
	}

	// .list-enter-active, .list-leave-active {
	//   transition: ease-out 1s;
	// }
	.list-enter,
		{
		opacity: 0;
		transform: translateY(100px);
	}

	.list-leave-to {
		opacity: 0;
		transform: translateY(10px);
	}

	.list-leave-active {
		position: absolute;
	}
</style>
